package com.core.EncryptedCommunication;


import com.common.anntation.SecurityParameter;
import com.common.config.Config;
import com.common.utils.AesEncryptUtils;
import com.common.utils.ServletUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 返回数据加密
 */
@RestControllerAdvice
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private final static Logger logger = LoggerFactory.getLogger(EncodeResponseBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (!Config.isFlag()){
            return body;
        }
        boolean encode = false;
        //方法不存在则在类上寻找注解则在类上寻找注解
        if (Objects.requireNonNull(methodParameter.getMethod()).isAnnotationPresent(SecurityParameter.class) || methodParameter.getDeclaringClass().isAnnotationPresent(SecurityParameter.class)) {
            //获取注解配置的包含和去除字段
            SecurityParameter serializedField = methodParameter.getMethodAnnotation(SecurityParameter.class);
            if (serializedField == null) {
                serializedField = methodParameter.getDeclaringClass().getAnnotation(SecurityParameter.class);
            }
            //出参是否需要加密
            if ((serializedField != null && serializedField.outEncode())) {
                encode = true;
            }
        }
        if (encode) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                final HttpServletRequest request = ServletUtils.getRequest();
                final String token = request.getHeader("Authorization");
                String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
                if (StringUtils.isNoneBlank(token)) {
                    return AesEncryptUtils.encrypt(result, token.substring(0, 16));
                } else {
                    return AesEncryptUtils.encrypt(result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return body;
    }
}